package com.windy.kafka.trace.listener;

import com.windy.common.context.HeaderContextHolder;
import com.windy.common.header.Headers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * Created by liyufeng on 2022/3/24
 */
@Slf4j
@ConditionalOnProperty(value = "com.windy.enable.kafka.listener", havingValue = "true", matchIfMissing = true)
@Component
public class KafkaMessageListener {
    @KafkaListener(topics = "test")
    public void onEventListener(@Payload String msg,
                                @Header(value = KafkaHeaders.TOPIC, required = false) String topic,
                                @Header(value = KafkaHeaders.MESSAGE_KEY, required = false) String key,
                                @Header(value = KafkaHeaders.PARTITION_ID, required = false) Integer partitionId,
                                @Header(value = "x-trace-id", required = false) String traceId) {
        try {
            log.info("receive msg : {} ,topic :{} ,key :{} ,partitionId :{},traceId:{}", msg, topic, key, partitionId, traceId);
            Headers header = HeaderContextHolder.getHeader();
            log.info("从threadLocal拿到的headers:{}", header.toString());
            throw new NullPointerException("测试异常");
        } finally {
            HeaderContextHolder.clear();
        }

    }
}
